import { Component, Injector, OnInit, ViewChild } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { SimpleTableColumn, SimpleTableComponent } from '@delon/abc';
import { deepCopy } from '@delon/util';
import {
  NzMessageService,
  NzModalService,
  NzNotificationService,
  NzTabChangeEvent,
  UploadFile,
} from 'ng-zorro-antd';
import { TranslateService } from '@ngx-translate/core';
import { PopService } from '../../../service/pop/pop.service';
import { of } from 'rxjs/index';
import { catchError } from 'rxjs/operators';
import { Constant, ServiceResult } from '@core/constant';
import { CommService } from '../../../service/comm/comm.service';
import { ProductService } from '../../../service/prod/product.service';
import { Router } from '@angular/router';

@Component({
  selector: 'pop-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../order/products/products.component.less'],
})
export class PopListComponent implements OnInit {
  // 设置抽屉是否可见
  visible = false;
  // 图片地址前缀
  imgSuffix = '';
  // 返回参数
  data = [];
  // checkbox 选中数组
  checkedList = [];
  // 定义按钮回调对象
  brands = [];
  record: any = {
    id: null,
    sku: null,
    description: null,
    brand: null,
    unit: null,
    qty: null,
    img: null,
    weight: null,
    exw: null,
    cif: null,
    status: null,
    priceUnit: null,
  };
  list = '';

  constructor(
    public http: _HttpClient,
    private msg: NzMessageService,
    private trans: TranslateService,
    private popService: PopService,
    private injector: Injector,
    private comm: CommService,
    private productService: ProductService,
    private router: Router,
    private modalService: NzModalService,
    private notice: NzNotificationService,
  ) {}

  ngOnInit() {
    this.imgSuffix = this.comm.getGoodsUrl();
    this.uploadUrl = this.productService.uploadUrl();
    this.list = this.popService.popMaintenanceList();
    this.st.load(1, this.q);
    this.loadBrands();
  }
  _onReuseInit() {
    this.list = this.popService.popMaintenanceList();
    this.st.load(1, this.q);
  }

  get cnt(): Constant {
    return this.injector.get(Constant);
  }

  close(): void {
    this.visible = false;
  }
  // 查询对象
  q: any = {
    sku: null,
    brand: null,
    id: null,
    status: null,
  };

  @ViewChild('st') st: SimpleTableComponent;
  columns: SimpleTableColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: 'SAP物料号', index: 'sap', i18n: 'sap' },
    { title: 'SKU描述', index: 'sku', i18n: 'sku_number' },
    { title: '品牌', index: 'brand', i18n: 'brand' },
    // { title: '描述', index: 'description', i18n: 'description' },
    { title: '图片', index: 'img', i18n: 'img', render: 'img' },
    { title: '库存', index: 'qty', i18n: 'qty' },
    // { title: '毛重', index: 'grossWeight', i18n: 'G.W.(Kg)' },
    // { title: '净重', index: 'netWeight', i18n: 'N.W.(Kg)' },
    { title: '装箱数', index: 'ctnQty', i18n: 'ctn_qty' },
    // { title: '外箱尺寸', index: 'cm', i18n: 'Box Size' },
    { title: 'EXW', index: 'exw', i18n: 'EXW' },
    // { title: 'CIF', index: 'cif', i18n: 'CIF' },
    {
      title: '价格单位',
      index: 'priceUnit',
      i18n: 'price_unit',
      render: 'priceUnit',
      tag: {
        USD: { text: 'USD', color: 'geekblue' },
        EUR: { text: 'EUR', color: 'orange' },
        '': { text: 'NO', color: 'purple' },
      },
    },
    {
      title: '状态',
      type: 'badge',
      index: 'status',
      i18n: 'status',
      badge: {
        disabled: { text: '下架', color: 'error' },
        normal: { text: '上架', color: 'success' },
        '': { text: 'null', color: 'default' },
      },
    },
    {
      title: '操作',
      i18n: 'operator',
      buttons: [
        {
          text: '编辑',
          i18n: 'edit',
          type: 'link',
          click: (record: any) =>
            this.router.navigate(['/pop/list/edit/' + record.id]),
        },
        {
          text: '查看',
          i18n: 'view',
          type: 'none',
          click: (record: any) => this.view(record),
        },
      ],
    },
  ];

  popDto: any = {
    id: null,
    sap: null,
    sku: null,
    description: null,
    img: null,
    unit: null,
    qty: null,
    netWeight: null,
    grossWeight: null,
    exw: null,
    cif: null,
    priceUnit: null,
    status: null,
    brand: null,
    ctnQty: null,
    cm: null,
    details: [],
  };
  selectUrl = null;
  panels = [];
  // 根据选中行查看内容
  view(record) {
    this.popService
      .listPopById(record.id)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(data => {
        this.popDto = data.data;
        // 拼接图片地址
        // this.selectUrl = this.comm.getGoodsUrl() + this.selectProduct.img;
        this.selectUrl = this.comm.getGoodsUrl() + this.popDto.img;
        if (this.popDto.details.length > 0) {
          this.panels = [];
          let flag = 0;
          for (const detail of this.popDto.details) {
            this.panels.push({
              detail: detail,
              active: flag === 0,
              disabled: false,
              name: 'POP Detail : ' + detail.sap,
              customStyle: {
                background: '#E9EBFE',
                'border-radius': '4px',
                'margin-bottom': '24px',
                border: '0px',
              },
            });
            flag++;
          }
        }
        this.visible = true;
      });
  }

  previewImage = '';
  previewVisible = false;

  showImage(src) {
    this.previewImage = src;
    this.previewVisible = true;
  }

  enable(id) {
    const lang = this.trans.currentLang || this.trans.defaultLang;
    this.popService
      .enable(id)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(ret => {
        if (ret.code === 200) {
          this.msg.create('success', lang === 'en' ? 'Successful' : '解禁成功');
          this.st.load(1, this.q);
        } else {
          this.msg.error(ret.msg);
        }
      });
  }

  disable(id) {
    const lang = this.trans.currentLang || this.trans.defaultLang;
    this.popService
      .disable(id)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(ret => {
        if (ret.code === 200) {
          this.msg.create('success', lang === 'en' ? 'Successful' : '禁用成功');
          this.st.load(1, this.q);
        } else {
          this.msg.error(ret.msg);
        }
      });
  }

  loading = false;
  // 预览图片地址
  picUrl = '';
  // 图片上传地址
  uploadUrl = '';
  // Excel批量导入地址
  uploadExcelUrl = this.popService.uploadPops();

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`不支持的格式: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.msg.warning('图片不能超过2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  };

  private getBase64(img: File, callback: (img: any) => void) {
    if (img) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
  }

  handleChange(info: { file: UploadFile }): void {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, () => {
        this.record.img = info.file.response.rows[0].id;
        this.picUrl = this.comm.getGoodsUrl() + this.record.img;
      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  changeTabs(args: NzTabChangeEvent) {
    switch (args.index) {
      case 0:
        this.q.status = null;
        break;
      case 1:
        this.q.status = this.cnt.PopStatusUtil.NORMAL;
        break;
      case 2:
        this.q.status = this.cnt.PopStatusUtil.DISABLED;
        break;
    }
    this.st.load(1, this.q);
  }

  manuallyAdd() {
    setTimeout(() => {
      this.router.navigate(['/pop/list/add']);
    }, 500);
  }
  manuallyAddPopItem() {
    setTimeout(() => {
      this.router.navigate(['/pop/list/addPopItem']);
    }, 500);
  }
  createPop() {
    setTimeout(() => {
      this.router.navigate(['/pop/list/pops']);
    }, 500);
  }
  managePopItem() {
    setTimeout(() => {
      this.router.navigate(['/pop/list/pops/list']);
    }, 500);
  }
  checkboxChange(list: any[]) {
    this.checkedList = list;
  }

  exportPop() {
    if (this.checkedList.length > 0) {
      this.st.export(this.checkedList, { filename: 'POP套餐清单.xlsx' });
    } else {
      let param = `?pageNumber=1&pageSize=0`;
      if (this.st.extraParams.sap) {
        param += '&sap=' + this.st.extraParams.sap;
      }
      if (this.st.extraParams.sap) {
        param += '&sku=' + this.st.extraParams.sku;
      }
      if (this.st.extraParams.brand) {
        param += '&brand=' + this.st.extraParams.brand;
      }
      this.st.export(this.list + param, { filename: 'POP套餐清单.xlsx' });
    }
  }
  showUpConfirm() {
    if (this.checkedList.length === 0) {
      this.msg.warning('请选择POP套餐');
      return;
    }

    this.modalService.confirm({
      nzTitle: `警告`,
      nzContent: `确定<span class="border-bottom-1 border-error">上架</span>选中的<b style="color: red;"> ${
        this.checkedList.length
      }</b> 项套餐?`,
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: () => this.batchUp(),
      nzCancelText: '取消',
    });
  }
  showDownConfirm() {
    if (this.checkedList.length === 0) {
      this.msg.warning('请选择POP套餐');
      return;
    }

    this.modalService.confirm({
      nzTitle: `警告`,
      nzContent: `确定<span class="border-bottom-1 border-error">下架</span>选中的<b style="color: red;"> ${
        this.checkedList.length
      }</b> 项套餐?`,
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: () => this.batchDown(),
      nzCancelText: '取消',
    });
  }

  // 批量下架
  private batchUp() {
    const ids = this.checkedList.map(v => v.id);
    this.popService
      .batchUp(ids.toString())
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(() => {
        this.st.reload();
        this.checkedList = [];
      });
  }
  // 批量下架
  private batchDown() {
    const ids = this.checkedList.map(v => v.id);
    this.popService
      .batchDown(ids.toString())
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(() => {
        this.st.reload();
        this.checkedList = [];
      });
  }

  loadBrands() {
    const lang = this.trans.currentLang || this.trans.defaultLang;
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult>data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.brands.push({
            text: lang === 'en' ? row.labelEnUs : row.labelDefault,
            value: row.value,
          });
        }
      }
    });
  }

  uploadProd(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
    }
    if (info.file.status === 'done') {
      this.loading = false;
      this.st.load();
      this.notice.create('success', '成功', '商品导入成功');
    }
    if (info.file.status === 'error') {
      this.loading = false;
      this.notice.create('error', '失败', '商品导入失败');
    }
  }
}
